#!/usr/bin/env bash

# go
export GO_LDFLAGS='-s -w -exldflags "-static"'

if command -v go >/dev/null; then
  export PATH=$(go env GOPATH)/bin:${PATH}
fi

go.build() {
  go build -trimpath -ldflags="${GO_LDFLAGS}" $@
}

go.mod.root() {
  dir=${1:-$(pwd)}
  while; do
    if [ -f "${dir}/go.mod" ]; then
      echo "${dir}"
      break
    fi
    parent=$(dirname ${dir})
    if [ "${dir}" = "${parent}" ]; then
      break
    fi
    dir=${parent}
  done
}

go.mod.rename() {
  cur=$(pwd)
  workdir=$(go.mod.root)
  if [ -z "${workdir}" ]; then
    echo "没找到 go module 目录"
    return
  fi
  o=$(cat go.mod | grep -E ^module | head -n 1 | awk '{print $2}')
  if [ -z "${o}" ]; then
    echo "不识别的东西"
    return 1
  fi
  n=$1
  if [ "${o}" = "${n}" ]; then
    echo "未更改: ${n}"
    return 0
  fi
  echo replace
  echo "old: ${o}"
  echo "new: ${n}"

  find . \( -name '*.go' -o -name 'go.mod' \) -exec sed -i '' "s#${o}#${n}#g" {} \;

  po=$(echo ${o} | awk -F '/' '{print $NF}')
  pn=$(echo ${n} | awk -F '/' '{print $NF}')
  if [ "${po}" != "${pn}" ]; then
    echo replace package
    echo "${po} => ${pn}"
    find . -depth 1 -name '*.go' -exec sed -i '' "s#package ${po}#package ${pn}#g" {} \;
  fi
  go mod tidy
  cd ${cur}
}

go.work.root() {
  dir=${1:-$(pwd)}
  while; do
    if [ -f "${dir}/go.work" ]; then
      echo "${dir}"
      break
    fi
    parent=$(dirname ${dir})
    if [ "${dir}" = "${parent}" ]; then
      break
    fi
    dir=${parent}
  done
}

go.work.sync() {
  cur=$(pwd)
  workdir=$(go.work.root)
  if [ -z "${workdir}" ]; then
    echo "没找到work目录"
    return
  fi
  echo ${workdir}
  cd ${workdir}

  # echo "go 1.18" >go.work
  rm -f go.work
  rm -f go.work.sum
  go work init

  IFS_OLD=IFS
  IFS=$'\n'
  for n in $(find . -name 'go.mod'); do
    n=$(echo ${n} | sed 's/\/go.mod//g')
    if [ "$n" = "." ]; then
      n="${n}/"
    fi
    echo $n
    go work edit -use $n
  done
  IFS=${IFS_OLD}
  rm -f go.work.sum
  go work sync
  cd ${cur}
}

go.sdk.last() {
  curl -SsL https://golang.google.cn/dl/\?mode\=json | grep -Eo 'go1\.([0-9]+)((\.|rc|beta)([0-9]*))?' | sed 's/rc/.0rc/g; s/beta/.0beta/g; s/$/.0s/g' | sort -ru | sed 's/.0rc/rc/g; s/.0beta/beta/g; s/.0s$//g'
}
